package com.jsy.order.controller;

import com.alibaba.fastjson.JSON;
import com.jsy.common.vo.Result;
import com.jsy.order.pojo.OrderItem;
import com.jsy.order.service.CartService;
import com.jsy.user.feign.UserFeign;
import com.jsy.user.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@RequestMapping("/cart")
public class CartController {

    /**
     * 将商品及购买数量加入到当前登录用户对应的购物车中
     * @param id 商品sku id
     * @param num 购买数量
     */
    @Autowired
    private CartService cartService;

    @Autowired
    private UserFeign userFeign;

    @GetMapping("/add")
    public Result add(String id, Integer num){
        try {
            //用户名
//            String username ="itheima";
            String username = SecurityContextHolder.getContext().getAuthentication().getName();
            cartService.add(id,num,username);
            return new Result("加入购物车成功！");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new Result("加入购物车失败！");
    }

    /**
     * 查看购物车列表
     */
    @GetMapping("/list")
    public Result<List<OrderItem>> list(){
        try {
            //用户名
//            String username ="itheima";
            //方式一，从security中获取管理员用户名
            String username = SecurityContextHolder.getContext().getAuthentication().getName();
            System.out.println("username = " + username);
            //方式二，从令牌中获取登录用户名
//            username= TokenDecode.getUserInfo().get("username");
//            System.out.println("username = " + username);
            List<OrderItem> list =cartService.list(username);
            //查询用户
            Result<User> userResult = userFeign.findById(username);
            System.out.println("userResult = " + JSON.toJSONString(userResult));
            return new Result<>("查看购物车列表成功！",list);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new Result<>("查看购物车列表失败！");
    }
}
